package com.example.sbeducation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sbeducation.dto.ChatMessageDTO;
import com.example.sbeducation.entity.ChatMessage;
import com.example.sbeducation.entity.User;
import com.example.sbeducation.exception.BusinessException;
import com.example.sbeducation.mapper.ChatMessageMapper;
import com.example.sbeducation.service.ChatMessageService;
import com.example.sbeducation.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 聊天消息服务实现类
 */
@Slf4j
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {

  @Autowired
  private UserService userService;

  @Override
  @Transactional
  public Long sendMessage(ChatMessageDTO chatMessageDTO) {
    // 验证发送者是否存在
    User sender = userService.getUserById(chatMessageDTO.getSenderId());

    // 验证接收者是否存在
    User receiver = userService.getUserById(chatMessageDTO.getReceiverId());

    // 创建消息
    ChatMessage chatMessage = new ChatMessage();
    BeanUtils.copyProperties(chatMessageDTO, chatMessage);
    chatMessage.setSendTime(LocalDateTime.now());
    chatMessage.setStatus(0); // 未读
    chatMessage.setCreateTime(LocalDateTime.now());
    chatMessage.setUpdateTime(LocalDateTime.now());
    chatMessage.setDeleted(0);

    // 保存
    save(chatMessage);

    return chatMessage.getId();
  }

  @Override
  public Page<ChatMessage> getChatHistory(Long senderId, Long receiverId, Integer page, Integer size) {
    // 查询聊天记录
    Page<ChatMessage> pageParam = new Page<>(page, size);
    LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();

    // 双向聊天记录
    queryWrapper.nested(i -> i.eq(ChatMessage::getSenderId, senderId)
        .eq(ChatMessage::getReceiverId, receiverId)).or(i -> i.eq(ChatMessage::getSenderId, receiverId)
            .eq(ChatMessage::getReceiverId, senderId));

    queryWrapper.orderByAsc(ChatMessage::getSendTime);

    return page(pageParam, queryWrapper);
  }

  @Override
  @Transactional
  public void markAsRead(Long messageId) {
    // 标记为已读
    ChatMessage chatMessage = getById(messageId);
    if (chatMessage == null) {
      log.warn("消息不存在: {}", messageId);
      return;
    }

    chatMessage.setStatus(1); // 已读
    chatMessage.setUpdateTime(LocalDateTime.now());

    updateById(chatMessage);
  }

  @Override
  @Transactional
  public void markAllAsRead(Long receiverId) {
    // 标记所有未读消息为已读
    LambdaUpdateWrapper<ChatMessage> updateWrapper = new LambdaUpdateWrapper<>();
    updateWrapper.eq(ChatMessage::getReceiverId, receiverId);
    updateWrapper.eq(ChatMessage::getStatus, 0); // 未读

    ChatMessage chatMessage = new ChatMessage();
    chatMessage.setStatus(1); // 已读
    chatMessage.setUpdateTime(LocalDateTime.now());

    update(chatMessage, updateWrapper);
  }

  @Override
  public Integer getUnreadCount(Long receiverId) {
    // 统计未读消息数量
    LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(ChatMessage::getReceiverId, receiverId);
    queryWrapper.eq(ChatMessage::getStatus, 0); // 未读

    return Math.toIntExact(count(queryWrapper));
  }

  @Override
  public List<ChatMessage> getUnreadMessages(Long receiverId) {
    // 获取未读消息
    LambdaQueryWrapper<ChatMessage> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(ChatMessage::getReceiverId, receiverId);
    queryWrapper.eq(ChatMessage::getStatus, 0); // 未读
    queryWrapper.orderByAsc(ChatMessage::getSendTime);

    return list(queryWrapper);
  }
}